import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormText, ProFormSelect, ModalForm, ProFormUploadDragger } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { deptList,savedept,updatedept,deletedept } from '../service';
import { Popconfirm,Button,message } from 'antd';
import { FileExcelOutlined } from '@ant-design/icons';
export default () => {
const [showCreate, setShowCreate] = useState(false);
const actionRef = useRef<ActionType>();
const [detail, setDetail] = useState<any>({});
const [showImport, setShowImport] = useState<boolean>(false);

const columns: ProColumns[] = [
   {
       title:'科室代码',
       dataIndex:'code',
       width:200,
       ellipsis:true,
   },
   {
       title:'科室名称',
       dataIndex:'name',
      //  width:100,
       ellipsis:true,
   },
   {
    title:'创建日期',
    dataIndex:'createDate',
    width:150,
    valueType:'date',
    hideInSearch:true,
   },
   {
    title:'创建人',
    dataIndex:'createUser',
    width:150,
    hideInSearch:true,
   },
   {
    title:'操作',
    valueType:'option',
    width:120,
    fixed: 'right',
    render: (text, record:any, _, action) => [
       <a key='detail' onClick={async () => {
       setDetail(record)
         setShowCreate(true)
       }}>详情</a>,
      //  record.deleteFlag=='1'?
       <Popconfirm title='确定要删除吗?' key='delete' onConfirm={() => handleDelete(record.id)}><a>删除</a></Popconfirm>
    ]}
   ]
   const handleDelete = async(id:string) => {
        var val = await deletedept({
          id: id,
        });

       if (val.errorCode === '200') {
           message.success('删除成功')
           actionRef.current?.reloadAndRest?.()
       } else {
          message.error(val.errorMessage)
       }
   };
   const onFileUpload = (info: any) => {
    if (info.file.status !== 'uploading') {}
    if (info.file.status === 'done') {
      if (info.file.response.errorCode === '200') {
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        actionRef.current?.reloadAndRest?.();
        setShowImport(false);
      } else {
        message.error('上传失败: ' + info.file.response.msg);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  };

return (<PageContainer>
    <ProTable actionRef={actionRef} headerTitle='列表' pagination={{pageSizeOptions: ['20', '100', '500']}}
        request={(params, sorter, filter) => deptList({ ...params,filter})} columns={columns} rowKey='id' toolbar={{settings: []}}
       search={{labelWidth: 120}} toolBarRender={() => [<Button type='primary' key='primary' onClick={() => {setShowCreate(true);setDetail(undefined)}}>新增</Button>,
       <Button type='primary' key='import' onClick={async () => {
        setShowImport(true);
      }}>
         <FileExcelOutlined/>导入
        </Button>]}
   />
  <DrawerForm title={detail ? '编辑' : '新增'} onVisibleChange={setShowCreate} visible={showCreate} drawerProps={{forceRender: true,destroyOnClose: true}} 
  onFinish={async (values: any) => {
    var val = undefined
    if (detail) {
      values.id = detail.id;
      val = await updatedept(values);
    } else {
      val = await savedept(values);
    }
    if (val.errorCode === '200') {
      message.success('提交成功');
      actionRef.current?.reloadAndRest?.();
      return true;
    } else {
      message.error(val.errorMessage);
      return false;
    }
  }}>
       <ProForm.Group>
           <ProFormText name='code' label='科室编码'  placeholder='请输入科室编码' width='md' initialValue={detail?.code}  />
       </ProForm.Group>
       <ProForm.Group>
           <ProFormText name='name' label='科室名称'  placeholder='请输入科室名称' width='md' initialValue={detail?.name} rules={[{required: true}]} />
       </ProForm.Group>
	  </DrawerForm>
    <ModalForm title='导入' onVisibleChange={v => {
      setShowImport(v);
    }} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} visible={showImport} onFinish={async (values: any) => {
      return true;
    }}>
             <div style={{
        margin: '10px 0 20px 0'
      }}><a href='/xwyl/attach/dept.xlsx' download='科室.xlsx'><Button type='primary'> <FileExcelOutlined/>科室模板下载</Button></a></div>
            <ProFormUploadDragger label='选择excel上传' name='file' action='/xwyl/hospitalDepartment/hospitalDepartmentImport' fieldProps={{
        name: 'file',
        headers: {
          'authorization': (sessionStorage.getItem('token') as string)
        }
      }} max={1} onChange={onFileUpload}/>

         </ModalForm>
   </PageContainer>
)}